import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../../large_data/CV2/lesson/Day07'
# img_name = 'hammer.jpg'
img_name = 'Moscow.jpeg'
# img_dir = '../../../../../large_data/pic'
# img_name = 'DSC05039.JPG'
# img_name = 'DSC05022_1.JPG'
# img_name = 'dog.jpg'
# img_name = 'dog_bird.jpg'
# img_name = 'football.jpg'
# img_name = 'messi5.jpg'
img_path = os.path.join(img_dir, img_name)

spr = 2
spc = 3
spn = 0
plt.figure(figsize=[9, 6])

sep('load')
img = cv.imread(img_path, cv.IMREAD_GRAYSCALE)
# img = cv.resize(img, None, fx=0.1, fy=0.1, interpolation=cv.INTER_CUBIC)
print('original shape', img.shape)
H, W = img.shape
H2 = H // 2
W2 = W // 2
my_show_img(img, 'original', cmap='gray')

# mask
mask = np.zeros((H, W), dtype=np.uint8)
H4 = H2 // 2
W4 = W2 // 2
mask[H2 - H4:H2 + H4, W2 - W4:W2 + W4] = 255
my_show_img(mask, 'mask', cmap='gray')

# mask it
masked = cv.bitwise_and(img, img, mask=mask)
my_show_img(masked, 'masked', cmap='gray')

# hist
hist = cv.calcHist([img], [0], None, [256], [0, 256])
hist_masked = cv.calcHist([img], [0], mask, [256], [0, 256])
spn += 1
plt.subplot(spr, spc, spn)
plt.plot(hist, color='r', label='hist')
plt.plot(hist_masked, color='y', label='hist masked')
plt.legend()
